package online.longzipeng.mywebdemo.utils;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * @author lzp
 * @Date:2023/6/7
 * @description: 文件工具类
 */
public class FileUtils {

	public static void main(String[] args) throws IOException {
		System.out.println(getImageFormat("https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKCVCniciaWgOBdNl0iaZZib2ArWlb0ndceove41GTWV2RSjFqyIAWMEMNkLYTzh8YuCNzjVr3V8bW3Yw/132"));
	}

	/**
	 * 获取url地址对应图片的格式
	 *
	 * @param imageUrl 图片的url地址
	 */
	public static String getImageFormat(String imageUrl) throws IOException {
		// 从URL下载图片
		URL url = new URL(imageUrl);
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try (InputStream input = url.openConnection().getInputStream()) {
			byte[] buffer = new byte[1024];
			int n;
			while ((n = input.read(buffer)) != -1) {
				output.write(buffer, 0, n);
			}
		}
		byte[] bytes = output.toByteArray();
		// 判断文件头部是否为JPEG，如果是即返回JPEG
		if (bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xD8) {
			return "JPEG";
		}
		// 使用Image I/O API来识别图片格式
		ImageInputStream in = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes));
		try {
			ImageReader reader = ImageIO.getImageReaders(in).next();
			reader.setInput(in);
			return reader.getFormatName().toUpperCase();
		} finally {
			in.close();
		}
	}

}
